<?php
namespace Modules\Agent\Http\Controllers\Admin\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use \Modules\Agent\Entities\AgentLevel;

use Validator;
use ThrowException;
use DB;

class AgentLevelController extends Controller
{
    public function index(Request $req)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $options = $req->all();

        $options['order_by'] = ['level' => 'asc'];
        $options['with_count'] = ['agents'];

        $list = AgentLevel::getList($options);

        return $list->generateListResponse();
    }

    // 单个用户详情
    public function show(Request $req, $uuid)
    {
        $item = AgentLevel::getEntity([
            'uuid' => $uuid
        ]);

        $info = $item->getInfo();

        $info['is_agent_leader'] = $item->isAgentLeader();

        return [
            'info' => $info
        ];
    }

    // 创建分销等级
    public function store(Request $req)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        if (AgentLevel::where('level', $req->level)->first()) {
            ThrowException::Conflict('等级' . $req->level . '已存在，请使用其它等级值');
        }

        $info = $req->all();

        $item = AgentLevel::create($info);

        return [
            'id' => $item->id,
            'uuid' => $item->uuid
        ];
    }

    // 更新用户信息
    public function update(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = AgentLevel::getEntity([
            'uuid' => $uuid
        ]);

        DB::beginTransaction();

        if ($req->type === 'update') {
            $info = $req->input('attributes');

            if (AgentLevel::where('level', $info['level'])->where('id', '<>', $item->id)->first()) {
                ThrowException::Conflict('等级' . $info['level'] . '已存在，请使用其它等级值');
            }

            $item->update($info);
        }
        elseif ($req->type === 'update_brokerage_setting')  {
            $item->update([
                'brokerage_setting' => $req->setting
            ]);
        }

        DB::commit();

        return [];
    }

    public function destroy(Request $req, $uuid)
    {
        $item = AgentLevel::getEntity([
            'uuid' => $uuid
        ]);

        $item->delete();

        return [];
    }
}
